package cn.huanba.utils;


import cn.huanba.config.SmsConfig;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/***
 * 短信发送工具类
 */
@Component
public class SmsUtils {

    @Autowired
    private SmsConfig smsConfig;
    /***
     * 发送短信的方法
     * @param
     * @return
     */
    public boolean sendMessage(String phone,String templateCode,String code) {
        //构造一个acs的clinet
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        //构造请求的request
        CommonRequest request = new CommonRequest();
        //设置了一堆参数

        request.setMethod(MethodType.POST);
        request.setDomain(smsConfig.getDomain());
        request.setVersion(smsConfig.getVersion());
        request.setAction(smsConfig.getAction());
        request.putQueryParameter("RegionId", smsConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", smsConfig.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        Map<String,String> map=new HashMap<String,String>();
        map.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            //发送请求，接收响应
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String status= (String) JSONObject.parseObject(response.getData()).get("Code");
            return "OK".equals(status);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
